"""this script parse the content of a xml file"""
import time

from bsp.devices.dev_serial import Ser
from utility.convert import Convert


class MWSerial():
    """
        串口中间层
    """
    def __init__(self):
        """
        指定串口
        """
        self.ser = Ser()
        self.convert = Convert()

    def open(self, serial_name, parity_bit="N", baud_rate=115200):
        """
        打开串口
        :param  serial_hanlde,serial_name:串口句柄,指定要使用的串口
        :param  parity_bit,baud_rate:校验位,波特率
        :return serial_hanlde:串口句柄
        """
        return self.ser.open(serial_name, parity_bit, baud_rate)

    def close(self, serial_hanlde):
        """
        关闭串口
        :param serial_hanlde:串口句柄
        :return:None
        """
        self.ser.close(serial_hanlde)

    def search(self):
        """
        搜索串口
        :param :None
        :return:serial_hanlde:串口句柄
        """
        return self.ser.search()

    def read(self, serial_hanlde, tmout=0.1):
        """
        读串口数据--16进制数据
        :param  serial_hanlde:串口句柄
        :return rcv_data:接收的数据
        """
        for i in range(3):
            try:
                rcv_data = self.ser.read(serial_hanlde)
                if rcv_data:
                    return rcv_data
                time.sleep(tmout)
            except IOError:
                return b''
        return b''

    def readline(self, serial_hanlde, tmout=0.1):
        """
        读串口数据--16进制数据
        :param  serial_hanlde:串口句柄
        :return rcv_data:接收的数据
        """
        for i in range(3):
            try:
                rcv_data = self.ser.readline(serial_hanlde)
                if rcv_data:
                    return rcv_data
                time.sleep(tmout)
            except IOError:
                return b''
        return b''

    def write(self, serial_hanlde, send_data):
        """
        写串口数据
        :param  serial_hanlde,send_data,timeout:串口句柄,发送的数据,超时时间
        :return rcv_data:接收的数据
        """
        for i in range(3):
            try:
                if self.ser.write(serial_hanlde, send_data) is True:
                    return True
                else:
                    return False
            except IOError:
                return False
        return False

    def read_write(self, serial_hanlde, send_data, tmout=0.01):
        """
        读写串口数据
        :param  serial_hanlde,send_data,timeout:串口句柄,发送的数据,超时时间
        :return rcv_data:接收的数据
        """
        for i in range(3):
            try:
                if self.ser.write(serial_hanlde, send_data) is True:
                    rcv_data = self.ser.read(serial_hanlde)
                    if rcv_data:
                        return self.convert.bytes_to_list(rcv_data)
                    time.sleep(tmout)
                else:
                    return []
            except IOError:
                return []
        return []
